package com.newvpn.fastbest.zenith.vpn;

import android.app.Activity;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.shadowsocks.Core;

import com.github.shadowsocks.aidl.IShadowsocksService;
import com.github.shadowsocks.aidl.ShadowsocksConnection;
import com.github.shadowsocks.aidl.TrafficStats;
import com.github.shadowsocks.bg.BaseService;
import com.github.shadowsocks.database.Profile;
import com.github.shadowsocks.database.ProfileManager;
import com.github.shadowsocks.preference.DataStore;
import com.newvpn.fastbest.zenith.activity.MainActivity;
import com.newvpn.fastbest.zenith.beans.netbeans.NetServerListBean;
import com.newvpn.fastbest.zenith.notify.NotifyHelper;
import com.newvpn.fastbest.zenith.utils.VLog;

public class SSManager {

    MainActivity mActivity;
    Profile profile;

    private ShadowsocksConnection connection;


    public SSManager(MainActivity activity) {

        mActivity = activity;
        VLog.e("SSManager inits");
        connection = new ShadowsocksConnection(true);
        connection.setBandwidthTimeout(500);
        //connection.disconnect(activity);
        initConnect();

    }

    private void initConnect() {
        connection.connect(mActivity, new ShadowsocksConnection.Callback() {
            @Override
            public void stateChanged(@NonNull BaseService.State state, @Nullable String s, @Nullable String s1) {
                VLog.e(state.toString()+","+s+","+s1);
                if (BaseService.State.Connected.equals(state)){
                    if (mVpnCallback != null){
                        mVpnCallback.success();
                    }
                }else if (BaseService.State.Stopped.equals(state)){
                    if (mVpnCallback != null){
                        mVpnCallback.stop();
                    }
                }
            }

            @Override
            public void trafficUpdated(long l, @NonNull TrafficStats trafficStats) {
                //Log.e("SSManager","trafficUpdated:"+trafficStats.getTxRate()+","+","+trafficStats.getRxRate());
                //NotifyHelper.send(mActivity.getApplicationContext(),trafficStats.getTxRate()+"",trafficStats.getRxRate()+"");
                if (mVpnCallback != null){
                    mVpnCallback.trafficUpdated(trafficStats.getTxRate(), trafficStats.getRxRate());
                }
            }

            @Override
            public void trafficPersisted(long l) {

            }

            @Override
            public void onServiceConnected(@NonNull IShadowsocksService iShadowsocksService) {
                VLog.e("onServiceConnected");
                try {
                    if (connection.getService().getState() == 2){
                        //需要恢复连接状态
                        if (mActivity != null){
                            mActivity.restartConnectedStatus();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected() {
                VLog.e("onServiceDisconnected");
            }

            @Override
            public void onBinderDied() {
                VLog.e("onBinderDied");
                connection.disconnect(mActivity);
                initConnect();
            }
        });
    }

    VPNCallback mVpnCallback;

    public void startVPN(String ip,NetServerListBean.ServiceInfoDetail server, VPNCallback vpnCallback,boolean hasConnected) {
        mVpnCallback = vpnCallback;
        if (hasConnected){
            return;
        }
        try {
            profile = new Profile();
            profile.setPassword(server.password);
            profile.setHost(ip);
            profile.setRemotePort(server.port);
            profile.setMethod(server.method);
            profile.setIndividual(DataStore.INSTANCE.getIndividual());
            profile.setBypass(true);
            profile.setDirty(true);
            profile.setProxyApps(true);
            ProfileManager.INSTANCE.createProfile(profile);
            Core.INSTANCE.switchProfile(profile.getId());
            Core.INSTANCE.startService();
        }catch (Exception e){
           e.printStackTrace();
        }

    }

    public void stopVPN() {
        Core.INSTANCE.stopService();
        try {
            ProfileManager.INSTANCE.delProfile(profile.getId());
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void unbindService(Activity activity) {
        if (connection != null) {
            activity.unbindService(connection);
            connection = null; // 重要：设置为null
        }

    }

//    public void setVPNLiveLister(JSONArray params, VPNLiveCallback vpnLiveCallback) {
//
//    }


}
